// 导入 vue
import Vue from 'vue'
// 导入 vuex
import Vuex from 'vuex'
// vuex也是vue的插件, 需要use一下, 进行插件的安装初始化
Vue.use(Vuex)

// 创建仓库 store
const store = new Vuex.Store({
  state: {
    goodList: [
      {
        name: '诸葛亮',
        price: 1000,
        num: 1,
        checked: false,
      },
      {
        name: '蔡文姬',
        price: 1500,
        num: 1,
        checked: false,
      },
      {
        name: '妲己',
        price: 2000,
        num: 1,
        checked: false,
      },
      {
        name: '鲁班',
        price: 2200,
        num: 1,
        checked: false,
      },
    ],
  },
  mutations: {
    updateCount(state, payload) {
      const player = state.goodList.find((item) => item.name === payload.name)
      player.num = payload.count
    },
    updateList(state, payload) {
      state.goodList = state.goodList.filter((item) => item.name !== payload)
    },
    updateCheck(state, payload) {
      const player = state.goodList.find((item) => item.name === payload.name)
      player.checked = payload.checked
    },
    changeAll(state, payload) { 
      state.goodList.forEach(item=>item.checked = payload)
    }
  },
  getters: {
    total(state) {
      const arr = state.goodList.filter((item) => item.checked)
      return arr.reduce((sum, item) => {
        return sum + item.num * item.price
      }, 0)
    },
    isAll(state) {
      return state.goodList.every(item=>item.checked)
    }
  },
})

// 导出仓库
export default store
